package com.imooc.utils;

import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description
 * @Author 顾志杰
 * @Date 2022/12/30 08:47
 */
public class EasyExcel {

  /**
   * 模版导出
   * @param response
   * @throws Exception
   */
  public void export(HttpServletResponse response) throws Exception {
    HashMap<String, String> mapa = new HashMap<>();
    mapa.put("name","张三");
    mapa.put("code","001");
    HashMap<String, String> mapb = new HashMap<>();
    mapb.put("name","李四");
    mapb.put("code","002");
    // 注意Map的key必须和模板保持一致,举例是name 和code
    List<Map<String, String>> excelList = Arrays.asList(mapa,mapb);
    // 设置响应类型
    response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    // 设置编码格式
    response.setCharacterEncoding("utf-8");

    long currentTime=System.currentTimeMillis();
    // 设置URLEncoder.encode 防止中文乱码
    String fileName = URLEncoder.encode("11-" + currentTime, "UTF-8").replaceAll("\\+", "%20");
    // 设置响应头
    response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

    // 使用模板填充表格，这里将表格预制到代码resources下面了，可以根据需求预制到其他地方，绝对路径和相对路径都可。 占位符 {.code}
    Resource resource = new ClassPathResource("b.xlsx");
    String templateFileName = resource.getFile().getPath();

    // 生成工作簿对象
    ExcelWriterBuilder workBookWriter = com.alibaba.excel.EasyExcel.write(response.getOutputStream())
      .withTemplate(templateFileName);
    // 创建工作表对象
    ExcelWriterSheetBuilder sheet = workBookWriter.sheet(0);
    sheet.doFill(excelList);

  }

  /**
   * 导入
   * @param file
   * @throws Exception
   */
  public void personImport(MultipartFile file) throws Exception {
    // 1.解析Excel
    ExcelListen readListener = new ExcelListen();
    com.alibaba.excel.EasyExcel.read(file.getInputStream(), readListener).sheet(0).doRead();
    readListener.getData().forEach(System.out::println);
  }
}
